/**
 * @file string.c
 * @date 230426
 * @author xin
 * @brief 字符串与内存空间赋值相关操作
 * @version 0.1
 * @status Stable
*/

#include "types.h"
#include "defs.h"

void *
memset(void *dst, int c, uint n)
{
    char *c_dst = (char*) dst;
    int i;
    for (i = 0; i < n; i++) {
        c_dst[i] = c;
    }
    return dst;
}

char*
safestrcpy(char* s, const char* t, int n)
{
    char *os;
    os = s;
    if (n <= 0) return os;
    while (--n > 0 && (*s++ = *t++) != 0);
    *s = 0;
    return os;
}

int 
strlen(const char *s)
{
    int n;
    for (n = 0; s[n]; n++); // 不包含'\0'
    return n;
}

void*
memmove(void *dst, const void *src, uint n)
{
    const char *s;
    char *d;

    if (n == 0) return dst;

    s = src;
    d = dst;
    if (s < d && s + n > d) {
        s += n;
        d += n;
        while (n-- > 0)
        {
            *--d = *--s;
        }
    } else 
        while (n-- > 0)
        {
            *d++ = *s++;
        }
    return dst;
}

int
strncmp(const char *p, const char *q, uint n)
{
    while (n > 0 && *p && *p == *q)
    {
        n--;
        p++;
        q++;
    }
    if (n == 0) return 0;
    return (uchar) *p - (uchar) *q;
}

char*
strncpy(char *s, const char *t, int n)
{
    char *os;

    os = s;
    while (n-- > 0 && (*s++ = *t++) != 0);
    while (n-- > 0)
        *s++ = 0;
    return os;
}